package dc.connectionmanager.logic;

import java.awt.EventQueue;
import java.util.ArrayList;

public class PlattformUpdater extends Thread
{
    private IConnectionManager cm;
    ArrayList<IUpdaterConnStatus> triggerConnStatusList;
    ArrayList<IUpdaterTriggerFunc> triggerFuncList;
    //private int counter = 0;
    
    
    public PlattformUpdater(IConnectionManager cmHandle)
    {
        this.cm = cmHandle;
        this.triggerConnStatusList = new ArrayList<IUpdaterConnStatus>();
        this.triggerFuncList = new ArrayList<IUpdaterTriggerFunc>();
        
        this.start();
    }
    
    public void registerTriggerConnStatusObj(IUpdaterConnStatus obj)
    {
        this.triggerConnStatusList.add(obj);
    }
    
    public void registerTriggerFunctionObj(IUpdaterTriggerFunc obj)
    {
        this.triggerFuncList.add(obj);
    }
    
    @SuppressWarnings("static-access")
    public void run()
    {
        while(true)
        {
            final boolean connected = cm.isConnected();
            
            //Pr�fen ob ConnectionManager Verbunden ist
            if(!connected)
            {
                if(cm.isReachable())
                {
                    cm.startConnection();
                }
            }
            else
            {
            	if(cm.getCountConnections() < cm.getMinConnection())
            	{
            		for(int i = 0; i < cm.getMinConnection(); ++i)
                    {
                        cm.startConnection();
                    }
            	}
            }
            
            for(int i = 0; i < this.triggerConnStatusList.size(); ++i)
            {
                final int step = i;
                EventQueue.invokeLater( new Runnable()
                {
                  public void run() 
                  {
                      triggerConnStatusList.get(step).handleConnectionStatus(connected);
                  }
                });
                
               
            }
            
            for(int i = 0; i < this.triggerFuncList.size(); ++i)
            {
                final int step = i;
                EventQueue.invokeLater( new Runnable()
                {
                  public void run() 
                  {
                      triggerFuncList.get(step).handlerUpdateTrigger();
                  }
                } );
                
            }
                        
            cm.checkConnectionIdle();
            
            try
            {
                this.sleep(this.cm.getUpdaterInterval());
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }
}
